package org.itzf.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.itzf.utils.JwtUtil;
import org.itzf.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 请求开始前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            // 处理 token 为空或格式错误的情况
            response.setStatus(401);
            sendErrorResponse(response, "Token is missing or invalid format");
            return false;
        }
       
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            System.out.println("token 解析成功 ： " + claims);
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            System.out.println("token 解析失败： " + e.getMessage());
            response.setStatus(401);
            sendErrorResponse(response, "Token verification failed: " + e.getMessage());
            return false;
        }
    }

    // 发送错误响应
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"message\": \"" + message + "\"}");
    }

    // 请求结束后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            ThreadLocalUtil.remove();
        } catch (Exception e) {
            System.out.println("清除 ThreadLocal 数据时出错： " + e.getMessage());
        }
    }
}